var app = {
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    onDeviceReady: function() {
        //this.receivedEvent('deviceready');
        ready();
    },

    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

function ready() {
    var myApp = new Framework7();
    var $$ = Dom7;
    var reader = new FileReader();
    var url = 'http://36.110.45.42:8889';
    var avatarURL = url + '/avatars/';
    var avatarDefaultURL = 'img/avatar.jpg';
    var mainView = myApp.addView('.view-main');

    var socket = io.connect(url);
    var isInitiate = true;

    // 蓝牙搜索到的用户
    var aroundUsers = [];

    var screenWidth = screen.width;
    var screenHeight = screen.height;
    var avatarWidth = 48;
    var maxLength = (screenWidth > screenHeight ? screenHeight : screenWidth) / 2;
    var maxRSSI = 100;

    var conversationStarted = false;
    var myMessages = myApp.messages('.messages');
    var myMessagebar = myApp.messagebar('.messagebar');

    /**
     * 检测蓝牙是否可被发现
     */
    custom.bluetooth.getAdapterState(function (state) {
        if (state.discoverable !== true) {
            $$('.my-switch input').prop('checked', false);
            custom.bluetooth.requestDiscoverable(0);
        } else {
            $$('.my-switch input').prop('checked', true);
            startDiscovery();
        }

        var address = state.address;

        // 给当前 socket 添加 mac address 标识
        socket.emit('mac', {mac: address});

        // 根据 mac address 获取用户信息
        socket.emit('user', {mac: address});

    });

    /**
     * 蓝牙状态变化
     */
    custom.bluetooth.onAdapterStateChanged.addListener(function (data) {
        if (data.enabled === true) {
            $$('.my-switch input').prop('checked', true);
            // 开始搜索
            startDiscovery();
        } else if (data.enabled === false) {
            $$('.my-switch input').prop('checked', false);
            // TODO 初始化数据

        }
    });

    /**
     * 搜到一台新设备
     */
    custom.bluetooth.onDeviceAdded.addListener(function (data) {
        var user = {address: data.address, rssi: data.rssi};
        user.rssi = Math.abs(user.rssi) > maxRSSI ? maxRSSI : Math.abs(user.rssi);
        socket.emit('other user', {mac: user.address, extra: user});
    });

    /**
     * 重新搜索
     */
    $$('.my-reScan').on('click', function () {
        startDiscovery();

        if ($$('.speed-dial').hasClass('speed-dial-opened')) {
            $$('.speed-dial').removeClass('speed-dial-opened');
        }
    });

    /**
     * 蓝牙开关
     */
    $$('.my-switch').on('click', function () {
        if ($$('.my-switch input').prop('checked')) {
            // 关闭蓝牙
            custom.bluetooth.disable();
        } else {
            // 打开蓝牙
            custom.bluetooth.requestDiscoverable(0, function (state) {
                $$('.my-switch input').prop('checked', true);
            }, function (state) {
                $$('.my-switch input').prop('checked', false);
            });
        }
    });

    /**
     * 发送消息
     */
    $$('.messagebar .link').on('click', function () {
        $$('.messagebar textarea').focus();

        var messageText = myMessagebar.value().trim();
        if (messageText.length === 0) return;

        myMessagebar.clear();

        myMessages.addMessage({
            text: messageText,
            type: 'sent',
            avatar: $$('.my-overlay-avatar').attr('src'),
            name: $$('.my-overlay-username').text(),
            day: !conversationStarted ? 'Today' : false,
            time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false
        });

        var otherMacs = aroundUsers.map(function (value) {
            return value.address;
        });

        socket.emit('message', {macs: otherMacs, message: messageText});

        conversationStarted = true;
    });

    /**
     * 获取用户信息
     */
    socket.on('other user', function (data) {
        if (data !== null) {
            if (data.avatar === undefined || data.avatar === '') {
                user.avatar = avatarDefaultURL;
            }

            var r = Math.abs(data.rssi)/maxRSSI * maxLength;
            var randomRadian = Math.random() * 2 * Math.PI;
            data.left = screenWidth/2 + Math.cos(randomRadian) * r;
            data.top = screenHeight/2 - Math.sin(randomRadian) * r;
            aroundUsers.push(data);

            $$('.my-chatroom-numbers').text(aroundUsers.length + 1);

            var radarBox = $$('.my-radar .page-content');
            if (radarBox.length > 0) {
                var tDOM = $$('<div class="my-radar-avatars"></div>');
                tDOM.addClass('my-radar-avatars');
                tDOM.css({
                    'background-image': 'url(' + avatarURL + user.avatar + ')',
                    left: user.left - avatarWidth/2 + 'px',
                    top: user.top - avatarWidth/2 + 'px'
                });
                radarBox.append(tDOM);
            }
        }
    });

    /**
     * 修改头像
     */
    $$('.my-overlay-avatar').on('click', function () {
        var buttons = [
            {
                text: '从相册中选择',
                onClick: function () {
                    navigator.camera.getPicture(function (fileURL) {
                        $$('.my-overlay-avatar').attr('src', fileURL);
                        window.resolveLocalFileSystemURL(fileURL, function (entry) {
                            uploadAvatar(entry);
                        });

                    }, function () {

                    }, {
                        quality: 100,
                        sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                        allowEdit: true,
                        encodingType: Camera.MediaType.JPEG,
                        mediaType: Camera.MediaType.PICTURE,
                        targetWidth: 456,
                        targetHeight: 456,
                    });
                }
            },
            {
                text: '拍照',
                onClick: function () {
                    navigator.camera.getPicture(function (fileURL) {
                        $$('.my-overlay-avatar').attr('src', fileURL);
                        window.resolveLocalFileSystemURL(fileURL, function (entry) {
                            uploadAvatar(entry);
                        });
                    }, function () {

                    }, {
                        quality: 100,
                        sourceType: Camera.PictureSourceType.CAMERA,
                        allowEdit: true,
                        encodingType: Camera.MediaType.JPEG,
                        mediaType: Camera.MediaType.PICTURE,
                        targetWidth: 456,
                        targetHeight: 456,
                        saveToPhotoAlbum: false,
                    });
                }
            },
            {
                text: '取消',
                color: 'red'
            },
        ];
        myApp.actions(buttons);
    });

    /**
     * 修改用户名
     */
    $$('.my-overlay-username').on('click', function () {
        changeUserInfo($$('.my-overlay-username'), '用户名');
    });

    /**
     * 修改简介
     */
    $$('.my-overlay-intro').on('click', function () {
        changeUserInfo($$('.my-overlay-intro'), '简介');
    });

    /**
     * 返回键
     */
    document.addEventListener("backbutton", function () {
        if ($$('.messagebar textarea').is(':focus')) {
            $$('.messagebar textarea').blur();
        } else if ($$('.modal-text-input').is(':focus')) {
            $$('.modal-text-input').blur();
        } else if ($$('.modal').length > 0 || $$('.actions-modal').length > 0) {
            myApp.closeModal();
        } else if (mainView.history.length > 1) {
            StatusBar.show();
            mainView.back();
        } else if ($$('.framework7-root').hasClass('with-panel-left-reveal')) {
            myApp.closePanel();
        } else {
            navigator.app.exitApp();
        }
    }, false);

    /**
     * 打开radar.html
     */
    $$('.my-load-radar').on('click', function () {
        mainView.router.loadPage('radar.html');
        if ($$('.speed-dial').hasClass('speed-dial-opened')) {
            $$('.speed-dial').removeClass('speed-dial-opened');
        }
    });

    /**
     * radar.html加载后
     */
    myApp.onPageInit('about', function (page) {
        StatusBar.hide();

        var radarBox = $$('.my-radar .page-content');
        var avatarDOM = $$('<div class="my-radar-avatars"></div>');
        avatarDOM.addClass('my-radar-avatars');
        avatarDOM.css({
            'background-image': 'url(' + $$('.my-overlay-avatar').attr('src') + ')',
            left: (screenWidth/2 - avatarWidth/2) + 'px',
            top: (screenHeight/2 - avatarWidth/2) + 'px'
        });
        radarBox.append(avatarDOM);
        for (var i = 0, j = aroundUsers.length; i < j; i++) {
            var avatarDOM = $$('<div class="my-radar-avatars"></div>');
            avatarDOM.addClass('my-radar-avatars');
            avatarDOM.css({
                'background-image': 'url(' + avatarURL + aroundUsers[i].avatar + ')',
                left: (aroundUsers[i].left - avatarWidth/2) + 'px',
                top: (aroundUsers[i].top - avatarWidth/2) + 'px'
            });
            radarBox.append(avatarDOM);
        }
    });

    /**
     * 获取到用户信息
     */
    socket.on('user', function (data) {
        if (data !== null) {
            if (data.avatar && data.avatar !== '') {
                $$('.my-overlay-avatar').attr('src', avatarURL + data.avatar);
            }
            if (data.name && data.name !== '') {
                $$('.my-overlay-username').text(data.name);
                $$('.my-overlay-username').removeClass('my-overlay-non');
            }
            if (data.intro && data.intro !== '') {
                $$('.my-overlay-intro').text(data.intro);
                $$('.my-overlay-intro').removeClass('my-overlay-non');
            }
        }
    });

    /**
     * 接收消息
     */
    socket.on('message', function (data) {
        myMessages.addMessage({
            text: data.message,
            type: 'received',
            avatar: data.user.avatar !== undefined ? avatarURL + data.user.avatar : avatarDefaultURL,
            name: data.user.name ? data.user.name : '',
            day: !conversationStarted ? 'Today' : false,
            time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false
        });
        conversationStarted = true;
    });

    function changeUserInfo(DOM, text) {
        var oldValue = DOM.text().trim();
        if (DOM.hasClass('my-overlay-non')) {
            oldValue = '';
        }
        
        myApp.modal({
            title: text,
            text: '<div class="input-field"><input class="modal-text-input" type="text" placeholder="' + oldValue + '"value="' + oldValue + '"></div>',
            buttons: [
                {
                    text: '取消',
                },
                {
                    text: '确定',
                    onClick: function () {
                        var newValue = $$('.modal .modal-text-input').val().trim();
                        if (newValue !== '') {
                            DOM.removeClass('my-overlay-non');
                            DOM.text(newValue);

                            // 更新用户信息
                            if (text === '用户名') {
                                socket.emit('update user name', {name: newValue});
                            } else if (text === '简介') {
                                socket.emit('update user intro', {intro: newValue});
                            }
                        }
                    }
                }
            ]
        });
    }

    function uploadAvatar(fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
            reader.onloadend = function () {
                socket.emit('upload avatar', this.result);
            }
            reader.readAsDataURL(file) ;
        });

    }

    function startDiscovery() {
        aroundUsers = [];
        $$('.my-chatroom-numbers').text(aroundUsers.length + 1);
        custom.bluetooth.startDiscovery();
    }
}

app.initialize();